/**
 * 强制透明材质修复工具
 * 专门解决页面刷新后透明区域显示黑色的问题
 */

/**
 * 强制修复透明材质，确保立即生效
 */
function forceFixTransparentMaterials() {
    console.log('🔧 [强制修复] 开始强制修复所有透明材质...');
    
    // 尝试多种方式获取场景对象
    let scene = window.scene;
    
    // 如果window.scene不存在，尝试从其他地方获取
    if (!scene && window.manager && window.manager.scene) {
        scene = window.manager.scene;
        console.log('🔍 从window.manager.scene获取场景对象');
    }
    
    // 尝试从sceneTreeManager获取
    if (!scene && window.sceneTreeManager && window.sceneTreeManager.scene) {
        scene = window.sceneTreeManager.scene;
        console.log('🔍 从window.sceneTreeManager.scene获取场景对象');
    }
    
    // 尝试从THREE场景中获取
    if (!scene && window.THREE && window.THREE.Scene) {
        // 查找已创建的场景实例
        const allScenes = [];
        if (window.sceneTreeUI && window.sceneTreeUI.scene) {
            scene = window.sceneTreeUI.scene;
            console.log('🔍 从window.sceneTreeUI.scene获取场景对象');
        }
    }
    
    if (!scene) {
        console.warn('⚠️ 暂时无法获取场景对象，可能场景还未完全加载');
        console.log('💡 建议稍后手动执行 forceFixTransparentMaterials() 或等待自动重试');
        return 0;
    }
    
    console.log('✅ 成功获取场景对象，开始修复透明材质...');

    let fixedCount = 0;
    const fixedMaterials = new Set(); // 避免重复修复同一个材质

    scene.traverse((object) => {
        if (object.isMesh && object.material) {
            const materials = Array.isArray(object.material) ? object.material : [object.material];
            
            materials.forEach((material) => {
                // 避免重复修复同一个材质实例
                if (fixedMaterials.has(material)) {
                    return;
                }
                
                // 检查是否为透明材质
                const hasAlphaTransparency = material.transparent || 
                                           material.alphaTest > 0 || 
                                           material.opacity < 1 || 
                                           !!material.alphaMap;
                
                if (hasAlphaTransparency) {
                    const materialName = material.userData?.materialName || material.name || 'Unknown';
                    // console.log(`🔧 [强制修复] ${object.name} - ${materialName}`);
                    // console.log(`   修复前: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
                    
                    // 🔑 强制设置基础颜色为白色
                    material.color.setRGB(1.0, 1.0, 1.0);
                    
                    // 🔧 多重强制更新策略
                    material.needsUpdate = true;
                    
                    // 强制更新uniform
                    if (material.uniforms && material.uniforms.diffuse) {
                        material.uniforms.diffuse.value.setRGB(1.0, 1.0, 1.0);
                    }
                    
                    // 强制重新编译着色器
                    material.version++;
                    
                    // 标记材质已修复
                    fixedMaterials.add(material);
                    fixedCount++;
                    
                    // console.log(`   ✅ 强制修复完成: RGB(1.000, 1.000, 1.000)`);
                }
            });
        }
    });

    console.log(`🎨 [强制修复] 完成！修复了 ${fixedCount} 个透明材质`);
    
    // 强制触发多次渲染更新
    if (window.manager && window.manager.render) {
        window.manager.render();
        // 延迟再次渲染，确保更新生效
        setTimeout(() => {
            window.manager.render();
        }, 100);
        setTimeout(() => {
            window.manager.render();
        }, 500);
    }
    
    return fixedCount;
}

/**
 * 检查透明材质的实际渲染状态
 */
function checkTransparentMaterialsRenderState() {
    console.log('🔍 [渲染状态检查] 检查透明材质的实际渲染状态...');
    
    const scene = window.scene;
    if (!scene) {
        console.error('❌ 无法获取场景对象');
        return;
    }

    let checkCount = 0;
    const checkedMaterials = new Set();

    scene.traverse((object) => {
        if (object.isMesh && object.material) {
            const materials = Array.isArray(object.material) ? object.material : [object.material];
            
            materials.forEach((material) => {
                if (checkedMaterials.has(material)) {
                    return;
                }
                
                const hasAlphaTransparency = material.transparent || 
                                           material.alphaTest > 0 || 
                                           material.opacity < 1 || 
                                           !!material.alphaMap;
                
                if (hasAlphaTransparency) {
                    checkCount++;
                    const materialName = material.userData?.materialName || material.name || `Material_${checkCount}`;
                    
                    console.log(`\n🔍 ${object.name} - ${materialName}:`);
                    console.log(`   基础颜色: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
                    console.log(`   透明设置: opacity=${material.opacity}, alphaTest=${material.alphaTest}, transparent=${material.transparent}`);
                    console.log(`   材质版本: ${material.version}, needsUpdate: ${material.needsUpdate}`);
                    console.log(`   材质ID: ${material.id}, UUID: ${material.uuid}`);
                    
                    // 检查uniform状态
                    if (material.uniforms && material.uniforms.diffuse) {
                        const uniformColor = material.uniforms.diffuse.value;
                        console.log(`   Uniform颜色: RGB(${uniformColor.r.toFixed(3)}, ${uniformColor.g.toFixed(3)}, ${uniformColor.b.toFixed(3)})`);
                    }
                    
                    // 分析问题
                    const avgColor = (material.color.r + material.color.g + material.color.b) / 3;
                    if (avgColor < 0.5) {
                        console.log(`   ❌ 问题：基础颜色过暗，可能导致透明区域显示黑色`);
                    } else if (avgColor > 0.9) {
                        console.log(`   ✅ 正常：基础颜色为白色，透明区域应该正常`);
                    } else {
                        console.log(`   ⚠️ 注意：基础颜色为中等亮度，可能影响透明效果`);
                    }
                    
                    checkedMaterials.add(material);
                }
            });
        }
    });

    console.log(`\n📊 检查完成，共检查了 ${checkCount} 个透明材质`);
}

/**
 * 延迟强制修复（页面加载后自动执行）
 */
function delayedForceFixTransparency(delay = 1000, maxRetries = 5) {
    console.log(`⏰ [延迟强制修复] 将在 ${delay}ms 后执行强制修复...`);
    
    let retryCount = 0;
    
    function attemptFix() {
        console.log(`🚀 [延迟强制修复] 第${retryCount + 1}次尝试...`);
        const fixedCount = forceFixTransparentMaterials();
        
        if (fixedCount === 0 && retryCount < maxRetries) {
            retryCount++;
            const nextDelay = delay + (retryCount * 1000); // 递增延迟
            console.log(`🔄 [延迟强制修复] 场景未就绪，${nextDelay}ms后重试 (${retryCount}/${maxRetries})`);
            setTimeout(attemptFix, nextDelay);
        } else if (fixedCount > 0) {
            console.log(`✅ [延迟强制修复] 成功修复了${fixedCount}个透明材质`);
        } else {
            console.log(`⚠️ [延迟强制修复] 达到最大重试次数，请手动执行修复`);
        }
    }
    
    setTimeout(attemptFix, delay);
}

/**
 * 智能等待场景加载完成后执行修复
 */
function waitForSceneAndFix() {
    // console.log('⏳ [智能等待] 等待场景加载完成...');
    
    let checkCount = 0;
    const maxChecks = 20; // 最多检查20次
    
    function checkScene() {
        checkCount++;
        
        // 检查场景是否存在
        const scene = window.scene || 
                     (window.manager && window.manager.scene) ||
                     (window.sceneTreeManager && window.sceneTreeManager.scene);
        
        if (scene) {
            console.log(`✅ [智能等待] 场景已加载，开始修复透明材质...`);
            forceFixTransparentMaterials();
        } else if (checkCount < maxChecks) {
            // console.log(`⏳ [智能等待] 场景未就绪，继续等待... (${checkCount}/${maxChecks})`);
            setTimeout(checkScene, 500);
        } else {
            console.log(`⚠️ [智能等待] 等待超时，请手动执行 forceFixTransparentMaterials()`);
        }
    }
    
    checkScene();
}

// 暴露到全局
window.forceFixTransparentMaterials = forceFixTransparentMaterials;
window.checkTransparentMaterialsRenderState = checkTransparentMaterialsRenderState;
window.delayedForceFixTransparency = delayedForceFixTransparency;
window.waitForSceneAndFix = waitForSceneAndFix;

// 页面加载完成后使用智能等待方式执行修复
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        // 使用智能等待，确保场景加载完成
        setTimeout(waitForSceneAndFix, 1000);
    });
} else {
    setTimeout(waitForSceneAndFix, 1000);
}

console.log('🔧 强制透明材质修复工具已加载');
console.log('   使用方法:');
console.log('   - forceFixTransparentMaterials()        // 强制修复所有透明材质');
console.log('   - checkTransparentMaterialsRenderState() // 检查透明材质渲染状态');
console.log('   - waitForSceneAndFix()                  // 智能等待场景加载后修复');
console.log('   - delayedForceFixTransparency(delay)     // 延迟强制修复');
